package com.link.base.base.forum.service;

import com.link.base.base.forum.dao.mybatis.mapper.ForumMapper;
import com.link.base.base.forum.model.Forum;
import com.link.base.base.forum.model.ForumReplay;
import com.link.base.base.forum.model.People;
import com.link.base.base.common.dao.mybatis.mapper.AttachmentMapper;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.image.service.AppImageService;
import com.link.base.base.statistics.model.Statistics;
import com.link.base.base.statistics.service.StatisticsService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 论坛
 *
 * @author ouyangzhenqiang
 * @date 2018/11/7
 */
@Service
public class ForumServiceImpl extends BasicServiceImpl<Forum> implements ForumService {

    @Resource
    protected KeyGenerateService keyGenerateService;
    @Resource
    private ForumMapper forumMapper;
    @Resource
    private AttachmentMapper attachmentMapper;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private StatisticsService statisticsService;

    @Resource
    private AppImageService appImageService;

    @Override
    public BasicMapper<Forum> getBasicMapper() throws Exception {
        return forumMapper;
    }

    @Override
    public List<Forum> queryForumList(Forum record) throws Exception {
        List<Forum> list = forumMapper.queryForumListPage(record);
        for (Forum fr : list) {
            QueryParams head = new QueryParams();
            head.addFilter(new Filter("headId", String.valueOf(fr.getId())));
            head.setPageFlag(false);
            Attachment t = (Attachment) BasicModel.transformClass(Attachment.class, head);
            List<Attachment> attList = attachmentMapper.queryByExamplePage(t);
            if (attList != null && attList.size() > 0) {
                fr.setAttList(attList);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addForum(Forum record) throws Exception {
        if (record.getId() == null) {
            Long forumId = keyGenerateService.keyGenerate();
            record.setId(forumId);
        }
        forumMapper.forumInsert(record);

        //推送消息开始
        QueryParams qps = new QueryParams();
        qps.addFilter(new Filter("noteId", String.valueOf(record.getId())));
        qps.setPageFlag(false);
        People t = (People) BasicModel.transformClass(People.class, qps);
        List<People> list = forumMapper.queryPeopleOfForumByPage(t);
//        for (People people : list) {
//            //pushService.pushToUser("XXX发起了一条与您的主题讨论:"+record.getNoteTitle() ,people.getUserId());
//        }
        //推送消息结束
    }

    /**
     * 重写insert方法，新建帖子的同时上传相关图片
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void insert(Forum record) throws Exception {
        if (record.getId() == null) {
            Long forumId = keyGenerateService.keyGenerate();
            record.setId(forumId);
        }
        // 插入记录
        forumMapper.forumInsert(record);

        // 上传帖子相关的图片
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void forumDelete(Forum record) throws Exception {
        if (record.getId() == null) {
            throw new Exception("获取不到id");
        }
        //删除主题附件开始
        QueryParams head = new QueryParams();
        head.addFilter(new Filter("headId", String.valueOf(record.getId())));
        head.setPageFlag(false);
        Attachment t = (Attachment) BasicModel.transformClass(Attachment.class, head);

        List<Attachment> attList = attachmentMapper.queryByExamplePage(t);
        for (Attachment att : attList) {
            attachmentService.deleteById(att);
        }
        //删除主题附件结束
        //删除回复开始
        QueryParams replayQps = new QueryParams();
        replayQps.addFilter(new Filter("noteId", String.valueOf(record.getId())));
        //不分页
        replayQps.setPageFlag(false);

        ForumReplay forumReplay = (ForumReplay) BasicModel.transformClass(ForumReplay.class, replayQps);
        //查询所有回复
        List<ForumReplay> replayList = forumMapper.queryForumReplayPage(forumReplay);
        for (ForumReplay replay : replayList) {
            //遍历删除所有回复下的附件
            QueryParams attQps = new QueryParams();
            attQps.addFilter(new Filter("headId", String.valueOf(replay.getId())));
            attQps.setPageFlag(false);
            Attachment atta = (Attachment) BasicModel.transformClass(Attachment.class, attQps);
            //获取回复的所有附件
            List<Attachment> replayAttList = attachmentMapper.queryByExamplePage(atta);
            for (Attachment att : replayAttList) {
                attachmentService.deleteById(att);
            }
        }
        //根据主题id删除所有回复的表记录
        forumMapper.useNoteIdToForumReplayDelete(record);
        //删除回复结束
        //删除主题
        forumMapper.useIdToForumDelete(record);
        //删除主题结束
    }


    @Override
    public void updateForum(Forum record) throws Exception {
        if (record.getId() == null) {
            throw new ServiceException("PUBLIC-007");
        }
        forumMapper.forumUpdate(record);
    }

    @Override
    public List<ForumReplay> queryForumReplayPage(ForumReplay record) throws Exception {

        List<ForumReplay> list = forumMapper.queryForumReplayPage(record);
        //每个回复拥有的附件
        for (ForumReplay fr : list) {
            QueryParams head = new QueryParams();
            head.addFilter(new Filter("headId", String.valueOf(fr.getId())));
            head.setPageFlag(false);
            Attachment t = (Attachment) BasicModel.transformClass(Attachment.class, head);
            List<Attachment> attList = attachmentMapper.queryByExamplePage(t);
            if (attList != null && attList.size() > 0) {
                fr.setAttList(attList);
            }
        }

        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addReplayOfForum(ForumReplay record) throws Exception {
        Long id = keyGenerateService.keyGenerate();
        record.setId(id);
        //回复内容插入
        forumMapper.forumReplayInsert(record);
        Forum head = new Forum();
        head.setId(record.getNoteId());
        //更新回复数量
        forumMapper.forumReplyNumUpdate(head);
    }


    @Override
    public List<People> queryPeoplePage(People record) throws Exception {
        return forumMapper.queryPeoplePage(record);
    }

    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void forumPeopleInsert(Forum record) throws Exception {
        if (record.getPeopleList() != null) {
            for (People people : record.getPeopleList()) {
                people.setId(keyGenerateService.keyGenerate());
                //设置主题id
                people.setNoteId(record.getId());
                //先删后增，防止插入重复数据
                forumMapper.forumPeopleDelete(people);
                forumMapper.forumPeopleInsert(people);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void forumPeopleDelete(Forum record) throws Exception {
        if (record.getPeopleList() != null) {
            for (People people : record.getPeopleList()) {
                //设置主题id
                people.setNoteId(record.getId());
                forumMapper.forumPeopleDelete(people);
            }
        }
    }

    @Override
    public List<People> queryPeopleOfForumByPage(People record) throws Exception {
        return forumMapper.queryPeopleOfForumByPage(record);
    }

    /**
     * 查询各类型帖子数量
     *
     * @author lizt
     * 2017年4月26日
     */
    @Override
    public List<Forum> queryForumTypeNum(Forum record) throws Exception {
        return forumMapper.queryForumTypeNum(record);
    }

    @Override
    public void delForumReplyById(ForumReplay record) throws Exception {
        forumMapper.delForumReplyById(record);
        forumMapper.forumReplyMinusUpdate(record);
    }

    /**
     * 评论查询
     */
    @Override
    public List<ForumReplay> queryForumReplayList(ForumReplay record) throws Exception {
        return forumMapper.queryForumReplayList(record);
    }

    /**
     * 评论总数
     */
    @Override
    public int queryForumReplayListCount(ForumReplay record) throws Exception {
        return forumMapper.queryForumReplayListCount(record);
    }

    /**
     * 评论帖子
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void forumReplayInsert(ForumReplay record) throws Exception {
        Long id = record.getId();
        if (null == id) {
            // 记录Id
            record.setId(keyGenerateService.keyGenerate());
        }
        // 设置回帖人
        record.setUserName(UserUtil.getUser().getFirstName());
        // 插入回帖记录
        forumMapper.forumReplayInsert(record);
        // 更新帖子上的回复数
        forumMapper.forumNoteReplyNumUpdate(record);
    }

    @Override
    public void setStatisticsData(Forum record, Long userId) throws Exception {
        // 从Redis中获取知识库的浏览量、阅读人数、点赞量、收藏量
        Statistics statistics = statisticsService.getStatisticsByModuleRecord("forum", record.getId());
        record.setCollectNum(statistics.getCollectNum());
        record.setReadNum(statistics.getPageViewNum());
        record.setFavorNum(statistics.getThumbNum());
        record.setPageviews(statistics.getPageViewNum());
        if (null != userId) {
            // 从Redis中获取用户是否点赞、是否收藏
            statistics = statisticsService.getFlagByModuleAndUser("forum", record.getId(), userId);
            record.setCollectFlag(statistics.getIsCollect());
            record.setFavorFlag(statistics.getIsThumb());
        }
    }
}
